from pyspades.server import block_action
from pyspades.collision import distance_3d_vector
from commands import add, admin
from map import Map
from pyspades.constants import *
import commands

@admin
def delfloor(connection):
        if connection.clearflooring > 0:
            connection.clearflooring = 0
            return 'Floor wiper cancelled'
        else:
            connection.clearflooring = 1
            return 'Break first corner block'
add(delfloor)

def apply_script(protocol, connection, config):
    class clearfloorMakerConnection(connection):
        clearflooring = 0
        clearfloor_x = 0
        clearfloor_y = 0
        clearfloor_z = 0

        def clear_floor(self, first_x, first_y, first_z, second_x, second_y):
            for build_x in xrange(min(first_x , second_x) , max(first_x , second_x)+1):
                for build_y in xrange(min(first_y , second_y) , max(first_y , second_y)+1):
                    block_action.x = build_x
                    block_action.y = build_y
                    block_action.z = first_z
                    block_action.value = 1
                    self.protocol.send_contained(block_action, save = True)
                    self.protocol.map.remove_point(build_x, build_y, first_z)
            self.send_chat('Floor cleared!')

        def on_block_removed(self, x, y, z):
            if self.clearflooring == 2:
                if abs(self.clearfloor_x - x) > 32 or abs(self.clearfloor_y - y) > 32:
                    self.send_chat('Floor clear area is too large! Cancelled.')
                    self.clearflooring = 0
                elif self.clearfloor_z == z:
                    self.clear_floor(self.clearfloor_x, self.clearfloor_y, self.clearfloor_z, x, y)
                    self.clearflooring = 0
                else:
                    self.send_chat('Surface is uneven! Using first height.')
                    self.clear_floor(self.clearfloor_x, self.clearfloor_y, self.clearfloor_z, x, y)
                    self.clearflooring = 0
            if self.clearflooring == 1:
                self.clearfloor_x = x
                self.clearfloor_y = y
                self.clearfloor_z = z
                self.send_chat('Now break opposite corner block')
                self.clearflooring = 2
            return connection.on_block_removed(self, x, y, z)

                
    return protocol, clearfloorMakerConnection